import { plugin, AMessage } from 'alemonjs'
import { oImages } from '../api'

import { cwd } from '../config/metadata'
import { command } from '../config/command'
import { AppName } from '../app.config'

import readline from 'readline'
import { runInThisContext } from 'vm'

let c = false

export class xianyuhelp extends plugin {
  constructor() {
    super({
      dsc: '咸鱼插件帮助',
      priority: 5000,
      rule: [...command.help]
    })
  }

  async replyclose(e: AMessage) {
    if (c) {
      r1.close()
      c = false
    }
    reply(e)
  }
  async offreplyclose(e: AMessage) {
    e.reply('对话框已关闭')
    clearInterval(z)
    r1.close()
    c = false
  }

  async doushouqi(e: AMessage) {
    await image(e, 'doushouqi', { _res: cwd })
  }

  async guojixiangqi(e: AMessage) {
    await image(e, 'guojixiangqi', { _res: cwd })
  }

  async xiangqi(e: AMessage) {
    await image(e, 'xiangqi', { _res: cwd })
  }

  async saolei(e: AMessage) {
    await image(e, 'saolei', { _res: cwd })
  }

  async help(e: AMessage) {
    let _res = cwd
    _res = _res.replace(/\\/g, '/')
    await image(e, 'help', { _res: _res })
  }
}

/**
 * @param {*} e 消息对象
 * @param {*} flie 文件名称
 * @param {*} data 传入对象
 * @returns 发送帮助截图
 */
async function image(e: AMessage, flie: string, data: object) {
  flie = `/resources/html/help/${flie}.html`
  const img = await oImages(flie, data)
  console.log('img=', img)
  if (img) e.reply(img)
}

let r1: any

function rr() {
  return readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })
}

let z: any
/**
 * 定时5分钟关闭对话框
 */
function 定时器() {
  z = setInterval(() => {
    r1.close()
    console.log('对话框超时关闭')

    c = false
    clearInterval(z)
  }, 300000)
}

function reply(e: AMessage) {
  if (!c) {
    r1 = rr()
    定时器()
  }
  c = true
  r1.question(
    '输入内容回车发送，加上/可结束对话：\t',
    function (answer: string) {
      // 不加close，则不会结束
      // r1.close()
      let msg = answer.replace(/\//, '')
      e.reply(msg)
      if (/\//.test(answer)) {
        r1.close()
        c = false
      } else {
        reply(e)
      }
    }
  )
}

// //close事件监听
// r1.on('close', function () {})
